//没有年月日
#include <rclcpp/rclcpp.hpp>
#include <my_custom_msgs/msg/time_info.hpp>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctime>

using namespace std::chrono_literals;

class TimePublisherNode : public rclcpp::Node
{
public:
    TimePublisherNode() : Node("time_publisher")
    {
        // 发布器
        publisher_ = this->create_publisher<my_custom_msgs::msg::TimeInfo>("time_info", 10);

        // 起始时间（steady_clock 用于精准计时）
        start_time_ = std::chrono::steady_clock::now();

        // 每秒发布一次
        timer_ = this->create_wall_timer(1s, std::bind(&TimePublisherNode::timer_callback, this));
    }

private:
    void timer_callback()
    {
        // 1) 当前时间（转为 YYYYMMDDHHMMSS）
        auto now_sys = std::chrono::system_clock::now();
        std::time_t now_c = std::chrono::system_clock::to_time_t(now_sys);
        std::tm tm_local{};
#ifdef _WIN32
        localtime_s(&tm_local, &now_c);
#else
        tm_local = *std::localtime(&now_c);
#endif
        std::ostringstream oss_time;
        oss_time << std::put_time(&tm_local, "%Y%m%d%H%M%S");
        std::string current_time_str = oss_time.str();

        // 2) 经过时间（转为 HH:MM:SS ，小时不限制位数，分秒补零）
        auto elapsed = std::chrono::steady_clock::now() - start_time_;
        long long elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(elapsed).count();
        long long hours   =  elapsed_seconds / 3600;
        int        minutes = (elapsed_seconds % 3600) / 60;
        int        seconds =  elapsed_seconds % 60;

        std::ostringstream oss_elapsed;
        // 小时不固定宽度（可超 24/99），分秒两位补零
        oss_elapsed << hours << ":"
                    << std::setw(2) << std::setfill('0') << minutes << ":"
                    << std::setw(2) << std::setfill('0') << seconds;
        std::string elapsed_time_str = oss_elapsed.str();

        // 3) 发布
        my_custom_msgs::msg::TimeInfo msg;
        msg.current_time = current_time_str;  // e.g. "20250825002301"
        msg.elapsed_time = elapsed_time_str;  // e.g. "01:02:05"
        publisher_->publish(msg);
    }

    rclcpp::Publisher<my_custom_msgs::msg::TimeInfo>::SharedPtr publisher_;
    rclcpp::TimerBase::SharedPtr timer_;
    std::chrono::steady_clock::time_point start_time_;
};

int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    rclcpp::spin(std::make_shared<TimePublisherNode>());
    rclcpp::shutdown();
    return 0;
}
